﻿; (function($) {
	// Private functions.
	var p = {};
	p.stop = function(evt) { if (evt) { $(this).addClass(p._opts.on); }; window.clearInterval(p._intervalID); };
	p.slide = function() {
		if (p._opts.dir == 1) {
			p._i.filter(":last").hide().fadeIn(p._opts.fadein).prependTo(p._t);
		} else {
			if (p._opts.vnum < p._cnt) {
				p._i.filter(":first").fadeOut(p._opts.fadeout).appendTo(p._t);
				p._i.filter(":eq(" + p._opts.vnum + ")").fadeIn(p._opts.fadein);
			} else {
				p._i.filter(":first").hide().appendTo(p._t).fadeIn(p._opts.fadein);
			};
		};
		//refresh
		p._i = $(p._opts.i, p._t);
		//visibility
		p._i.filter(":gt(" + (p._opts.vnum - 1) + ")").hide();
	}; //slide 
	p.go = function(evt) {
		p.stop();
		if (evt) {
			$(this).removeClass(p._opts.on);
		};
		p._intervalID = window.setInterval(function() { p.slide(); }, p._opts.interval);
	}; //go
	//main plugin body
	$.fn.xMarquee = function(options) {
		// Set the options.
		options = $.extend({}, $.fn.xMarquee.defaults, options);
		p._opts = options;
		// Go through the matched elements and return the jQuery object.
		return this.each(function() {
			//NOTE:if wanna support multiple marquee instance,we should cache private variable via $(this).data("v",v)
			p._t = this; //marquee target;
			//silde items
			p._i = $(p._opts.i, p._t);
			p._cnt = p._i.size();
			p._intervalID = null;
			//hide unwanted items
			p._i.filter(":gt(" + (p._opts.vnum - 1) + ")").hide();
			p._i.hover(p.stop, p.go);
			//buttons registeration
			$(p._opts.btn0).click(function(evt) { p._opts.dir = 0; p.stop(); p.slide(); return false; }).mouseout(p.go);
			$(p._opts.btn1).click(function(evt) { p._opts.dir = 1; p.stop(); p.slide(); return false; }).mouseout(p.go);
			
			//trigger the slidebox
			p.go();

		});
	};
	// Public defaults.
	$.fn.xMarquee.defaults = {
		on: 'cur',
		i: 'li', //slide items  css selector
		interval: 5000,
		fadein: 300,
		fadeout: 200,
		vnum: 4, //visible marquee items
		dir: 1, //marquee direaction.1=right;0=left;
		btn0: '.prev', //prev button
		btn1: '.next'//next button
	};
})(jQuery); 